﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Engine.Physics;

namespace Engine.Graphics
{
    public class ParticleSystem : Component
    {
        //Holds all settings
        public ParticleSystemData Data;

        public List<Particle> Particles { get; private set; }
        public bool Perspective = true;

        public int ParticleCount { get { return Particles.Count - freeIndices.Count; } }

        private List<int> freeIndices;
        private double timeSinceLastSpawned;

        #region Initialization
        public ParticleSystem()
        {
            Particles = new List<Particle>();
        }

        public ParticleSystem(ParticleSystemData _data)
        {
            Data = _data;
            freeIndices = new List<int>();
            Particles = new List<Particle>();
        }

        public ParticleSystem(string _presetName)
        {
            Data = ParticleSystemDatabase.ParticleSystemPresets[_presetName];
            Particles = new List<Particle>();
            freeIndices = new List<int>();
        }

        public override void OnAdd(GameObject _gameObject)
        {
            base.OnAdd(_gameObject);
            ParticleEngine.Instance.systems.Add(this);
        }

        public override void OnRemove()
        {
            ParticleEngine.Instance.systems.Remove(this);
            base.OnRemove();
        }

        #endregion

        #region Update/Draw Loop
        public override void Update(GameTime _gameTime)
        {
            if (IsActive)
            {
                timeSinceLastSpawned += _gameTime.ElapsedGameTime.TotalSeconds;

                while (timeSinceLastSpawned >= 60.0 / Data.ParticleSpawnRate)
                {
                    SpawnParticle();
                    timeSinceLastSpawned -= 60.0 / Data.ParticleSpawnRate;
                }

                if (timeSinceLastSpawned < 0)
                    timeSinceLastSpawned = 0;
            }

            foreach (Particle particle in Particles)
            {
                particle.Update(_gameTime, Data.StartScale, Data.animationColors, Data.EndScale, 0f, Data.EndRotation);
            }

            for (int i = Particles.Count -1; i >= 0; i--)
            {
                if (Particles[i].rigidbody.IsActive && Particles[i].Lifetime > Particles[i].MaxLifetime)
                {
                    Particles[i].SetActive(false);
                    freeIndices.Add(i);
                }
            }

            if (freeIndices.Count > Particles.Count / 2 -1)
            {
                freeIndices.Sort();
                for (int i = freeIndices.Count - 1; i >= 0; i--)
                {
                    PhysicsEngine.Instance.RemoveRigidbody(Particles[freeIndices[i]].rigidbody);
                    Particles.RemoveAt(freeIndices[i]);
                    freeIndices.RemoveAt(i);
                }
            }


        }

        public override void Draw()
        {
            float depth = 0;
            if (Perspective)
            {
                depth = 1;
            }

            foreach (Particle particle in Particles)
            {
                if (particle.rigidbody.IsActive)
                {
                    GraphicsEngine.Instance.DrawParticle(Data.ParticleTexture,
                        particle.rigidbody.Position,
                        particle.animation.CurrentFrameRect, particle.Color, particle.Scale, particle.Rotation, true,
                        depth);
                }
            }            
        }
        #endregion

        /// <summary>
        /// Spawns the given amount of particles instantly
        /// </summary>
        public void SpawnParticlesOneShot(int _particleCount)
        {
            for (int i = 0; i < _particleCount; i++)
            {
                SpawnParticle();
            }
        }

        private void SpawnParticle()
        {
            Vector2 spawnPosDiff = new Vector2((float)MathUtils.Random.NextDouble()*2 -1 , (float)MathUtils.Random.NextDouble()*2 -1);
            spawnPosDiff.Normalize();
            spawnPosDiff *= Data.SpawnRadius;

            if (Data.SpawnAreaType == SpawnArea.Line)
                spawnPosDiff.Y = 0;

            float lifetime = Data.MaxLifetime + Data.LifetimeRandom * ((float)MathUtils.Random.NextDouble() * 2 - 1);
            Vector2 direction = Data.StartDirection;
            float speed = Data.StartSpeed + Data.VelocityRandom * ((float)MathUtils.Random.NextDouble() * 2 - 1);
            Vector2 velocity = direction * speed;

            Animation anim = (Animation)Data.animation.Clone();
            anim.FramesPerSecond = (int)((anim.FrameCount/lifetime));
            if (freeIndices.Count == 0)
            {
                Particles.Add(new Particle(spawnPosDiff + Position, velocity, Data.StartScale, (float)(MathUtils.Random.NextDouble() * Math.PI), Data.EndRotation, Data.animationColors[0], lifetime, anim));
            }
            else
            {
                Particles[freeIndices[0]].SetActive(true);
                Particles[freeIndices[0]].SetValues(spawnPosDiff + Position, velocity, Data.StartScale, (float)(MathUtils.Random.NextDouble() * Math.PI), Data.EndRotation, Data.animationColors[0], lifetime, anim);
                
                freeIndices.RemoveAt(0);
            }
        }
        
    }
}
